package com.wangzeqi.neihanduanzi.home.essence;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.wangzeqi.neihanduanzi.R;
import com.wangzeqi.neihanduanzi.home.essence.entity.EssenceEntity;

/**
 * Created by dllo on 16/1/11.
 */
public class FragmentEssence extends Fragment {

    private Context context;
    private AdapterEssence adapter;
    private RecyclerView recyclerView;
    private RequestQueue queue;
        private EssenceEntity entity;
    private String url = "http://toutiao.com/ma/?media_id=5234320301&count=10&max_behot_time=0&callback=jsonp1&csrfmiddlewaretoken=undefined&_=1452080518176";

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.essence_fragment, null);
        recyclerView = (RecyclerView) view.findViewById(R.id.rv_essence);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new AdapterEssence(context);
        recyclerView.setAdapter(adapter);
        addData();

    }

    private void addData() {
        queue = Volley.newRequestQueue(context);
        final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
              String rps = response.substring(response.indexOf("{"), response.indexOf(")"));
                Gson gson = new Gson();
                entity = gson.fromJson(rps, EssenceEntity.class);
                adapter.addData(entity);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(request);
    }


}
